package com.hmall.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//@Component
public class DemoGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取当前请求对象
        ServerHttpRequest request = exchange.getRequest();
        
        // 获取请求的URI路径
        String uri = request.getPath().value();
        System.out.println("Request URI: " + uri);
        
        // 从请求头中获取User-Agent信息
        String userAgent = request.getHeaders().getFirst("User-Agent");
        System.out.println("User-Agent: " + userAgent);
        
        // 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //  如果要拦截不放行：
        //      设置响应状态码
        // response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //      立即终结并返回响应
        // return response.setComplete();
        // 继续执行过滤器链，将请求转发到下一个过滤器或目标服务
        // 放行

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        // 设置过滤器的执行顺序，数值越小优先级越高
        return 0;
    }
}
